package com.ibp.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ibp.entity.ProjectMgr;
import com.ibp.service.DictDataService;
import com.ibp.service.FSHttpService;
import com.ibp.service.ProjectMgrService;
import com.ibp.utils.PropertyUtils;
import com.ibp.utils.RegeUtils;
import com.ibp.utils.StringUtil;

/**
 * @author yf028
 * 
 */
@Service("projectMgrServiceImpl")
public class ProjectMgrServiceImpl implements ProjectMgrService,
		InitializingBean {

	private static final int recordLength = 4;

	private static Logger logger = LoggerFactory
			.getLogger(ProjectMgrServiceImpl.class);

	@Autowired
	PropertyUtils propertyUtils;

	@Autowired
	FSHttpService fSHttpServiceImpl;

	@Autowired
	DictDataService dictDataServiceImpl;
	private ServletContext servletContext; 

	private String ibms_ip = null;
	private String ibms_port = null;
	private String url = null;
	private String query_projects=null;
	private String add_projects=null;
	private String remove_projects=null;
	private String set_projects=null;
	
	
	/* 
	 * 
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		this.servletContext = dictDataServiceImpl.getServletContext();
	  	logger.info("初始化服务节点ip和port配置,servletContext:"+servletContext); 
	    Map<String,Map<String,String>> dictMap = (Map<String, Map<String, String>>) this.servletContext.getAttribute("dictMap");
	    
	    this.ibms_ip = 	  dictMap.get("http.ibms").get("ip");
	    this.ibms_port =  dictMap.get("http.ibms").get("port");
	    this.url = ("http://" + this.ibms_ip + ":" + this.ibms_port + "/");
	    this.query_projects= dictMap.get("http.ibms").get("query.projects");
	    this.add_projects= dictMap.get("http.ibms").get("add.projects");
	    this.remove_projects= dictMap.get("http.ibms").get("remove.projects");
	    this.set_projects= dictMap.get("http.ibms").get("set.projects");
	}

	/*
	 * 查询节点-交易码关系 filter 页面输入查询条件
	 */
	@Override
	public List<ProjectMgr> getProjectList(ProjectMgr filter) {
		List<ProjectMgr> projects = new ArrayList<ProjectMgr>();

		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.query_projects);
		if (!StringUtil.isEmpty(response)) {
			projects = parseResponse(response);
		}
		logger.debug("查询节点-交易码关系：{}", projects);
		// 过滤掉不符合条件的记录
		projects = filter(projects, filter);
		logger.debug("过滤后的节点-交易码关系：{}", projects);
		return projects;
	}

	/***
	 * 过滤结果集
	 * 
	 * @param projects待过滤的结果集
	 * @param filter
	 *            页面输入的搜索条件
	 * @return
	 */
	private List<ProjectMgr> filter(List<ProjectMgr> projects, ProjectMgr filter) {
		// 过滤条件全为空，不过滤结果，直接输出
		if (filter == null || StringUtils.isBlank(filter.getProject())
				&& StringUtils.isBlank(filter.getApps())
				&& StringUtils.isBlank(filter.getClient_nodes())
				&& StringUtils.isBlank(filter.getServer_nodes())) {
			return projects;
		}

		List<ProjectMgr> result = new ArrayList<ProjectMgr>();
		for (ProjectMgr pro : projects) {
			if (RegeUtils.match(pro.getProject(), filter.getProject())
					&& RegeUtils.match(pro.getClient_nodes(),
							filter.getClient_nodes())
					&& RegeUtils.match(pro.getServer_nodes(),
							filter.getServer_nodes())
					&& RegeUtils.match(pro.getApps(), filter.getApps())) {
				result.add(pro);
			}
		}
		return result;
	}

	// 检测服务节点和客户端节点的
	private boolean checkNodeList(List<String> nodes, List<String> filters) {
		if(filters==null || 0==filters.size()){
			return true;
		}
		
		String filt = filters.get(0);		
		for (String node : nodes) {			
			if(RegeUtils.match(node, filt)){
				return true;
			}
		}
		return false;
	}

	private <T> boolean isBlankList(List<T> t) {
		if (t == null || true == t.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	private List<ProjectMgr> parseResponse(String response) {
		// 检查入参
		if (StringUtils.isBlank(response)) {
			return null;
		}
		String[] respStr = response.split("\n");

		// 存放处理结果
		List<ProjectMgr> list = new ArrayList<ProjectMgr>();

		for (int i = 0; i < respStr.length; ++i) {
			ProjectMgr project = new ProjectMgr();
			String[] pro = respStr[i].split("\\|");

			logger.debug("查询结果的记录中的列数：{}", pro.length);
			if (recordLength == pro.length) {
				project.setProject(pro[0]);
				project.setServer_nodes(pro[1].substring(1));
				project.setClient_nodes(pro[2].substring(1));
				project.setApps(pro[3].substring(1));
				list.add(project);
			}
		}

		return list;

	}


	//删除proj
	@Override
	public void deleteProject(ProjectMgr project) {
		
		String paramsJson = objToJson(project);
		logger.debug("删除记录的主键json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.remove_projects, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("删除成功");
		}

	}
	
	private String format(List<String> list){
		StringBuffer strBuffer = new StringBuffer();
		for(String str: list){
			strBuffer.append(str + " ");
		}
		return strBuffer.toString();
		
	}

	//增加proj
	@Override
	public void addProject(ProjectMgr project) {
		String paramsJson = objToJson(project);

		logger.debug("增加记录json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.add_projects, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("增加成功");
		}

	}
	


	//更新proj
	@Override
	public void updateProject(ProjectMgr project) {
		String paramsJson = objToJson(project);
		logger.debug("修改记录json：{}", paramsJson);
		String response = this.fSHttpServiceImpl.sendPostRequest(this.url
				+ this.set_projects, paramsJson);
		if (!StringUtil.isEmpty(response)) {
			logger.debug("修改成功");
		}

	}
	
	
	//内部类，用于
	public String objToJson(Object obj) {
		return JSON.toJSONString(obj);

	}
	
}
